import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'umi';
import { Form, Table } from 'antd';

import Pagination from '@/components/Pagination';
import { utils } from 'vv-frontend-components';
import isEmpty from 'lodash/isEmpty';
import LinkTo from '@/components/LinkTo';
import TableFilter from '@/components/TableFilter';
// import styles from './index.less';
// AuthComponent AuthCode权限控制
// import AuthComponent from '@/utils/auth/AuthComponent';
// import AuthCode from '@/utils/auth/AuthCode';

// import AddCandidate from './AddCandidate'; // 添加候选人
import SetResult from './SetResult';

import CandidateSearchForm from './SearchForm';
import './index.less';

// 状态色
const dictColor = {
    applying: '#40A9FF', // 申请中
    apply_failed: '#F5222D', // "申请未通过"
    apply_success: '#52C41A', // 申请通过
    be_pending: '#40A9FF', // 待定
    eliminated: '#F5222D', // 淘汰
    entry_cancel: '#000', // 取消入职
    entry_success: '#52C41A', // 已入职
    offer_accepted: '#52C41A', // 已接受
    offer_refused: '#F5222D', // 已拒绝
    offer_sended: '#52C41A', // 已发送
    pass: '#52C41A', // 通过
    wait_for_beginning: '#d8d8d8', // "待开始"
    wait_for_processing: '#d8d8d8', // 待处理
    interview_cancel: '#d8d8d8' // 面试取消
};
// 应聘职位
// const renderOption = postTypeData => postTypeData.map(item => <Option value={item.dictValue}>{item.dictName}</Option>);

const getSexName = key => {
    if (key === '1') {
        return <i className="iconfont iconoa_table_icon_men_default" style={{ color: '#3aa0ff', margin: '0 5px' }} />;
    }
    if (key === '2') {
        return <i className="iconfont iconoa_table_icon_women_default" style={{ color: '#f2637b', margin: '0 5px' }} />;
    }
    return '';
};
// 列表项
const columns = ({
    stageList,
    scheduleList,
    setVisible,
    setCandicode,
    // setCandistage,
    // query,
    candidateStage,
    candidateState
}) => [
    {
        title: '姓名',
        dataIndex: 'talentName',
        key: 'talentName',
        width: 200,
        render(text, record) {
            return (
                <div style={{ display: 'flex' }}>
                    <LinkTo
                        to="/personal/portal/recruit/candidate/detail"
                        query={{
                            candidateCode: record.candidateCode
                            // formDeploymentId: record.formDeploymentId,
                            // id: record.id,
                            // processDeploymentId: record.processDeploymentId,
                            // templateId: record.templateId,
                            // templateName: record.templateName,
                            // applicationNo: record.applicationNo
                        }}
                        className="marginR"
                        style={{
                            display: 'inline-block',
                            maxWidth: '200px',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            verticalAlign: ' text-bottom'
                        }}
                        title={text}
                    >
                        {text}
                    </LinkTo>
                    {getSexName(record.talentSex)}
                </div>
            );
        }
    },
    {
        title: '应聘职位',
        dataIndex: 'recruitPost',
        key: 'recruitPost',
        width: 180
    },
    {
        title: '公司',
        dataIndex: 'companyName',
        key: 'companyName',
        width: 180
    },
    {
        title: '添加候选时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 180,
        sorter: () => {}
        // render(text, record) {
        //     return <span>{record.startTime}</span>;
        // }
    },
    {
        title: '阶段',
        dataIndex: 'candidateStageValue',
        key: 'candidateStageValue',
        filters: stageList,
        filteredValue: candidateStage,
        // ...filterValuesCfg,
        filterDropdown: filterProps => <TableFilter {...filterProps} />,
        filterMultiple: false,
        width: 180
    },
    {
        title: '状态',
        dataIndex: 'candidateStateValue',
        key: 'candidateStateValue',
        filters: scheduleList,
        // filteredValue: overTime,
        filteredValue: candidateState,
        filterDropdown: filterProps => <TableFilter {...filterProps} />,
        filterMultiple: false,
        width: 150,
        render(text, record) {
            return (
                <span>
                    <span
                        className="manaCircle"
                        style={{
                            backgroundColor: dictColor[record.candidateState]
                        }}
                    ></span>
                    {text}
                </span>
            );
        }
    },
    {
        title: <span style={{ whiteSpace: 'nowrap' }}>招聘负责</span>,
        dataIndex: 'candidateLeaderName',
        // width: 150,
        key: 'candidateLeaderName',
        render(text) {
            return <span style={{ whiteSpace: 'nowrap' }}>{text}</span>;
        }
    },
    {
        title: '操作',
        dataIndex: '',
        key: '',
        width: 150,
        fixed: 'right',
        render(text, record) {
            return (
                <span>
                    {record.isChoose ? (
                        <a
                            onClick={e => {
                                e.preventDefault();
                                setVisible(true);
                                setCandicode(record.candidateCode);
                                // setCandistage(record.candidateStage);
                            }}
                        >
                            设置筛选结果
                        </a>
                    ) : null}
                </span>
            );
        }
    }
];
const List = ({ activeKey, form, loading, recommend, common, dispatch, location, route }) => {
    // 过滤高级搜索空格
    const { deepTrim } = utils;
    const { query } = location;
    const { pagination, recommendList: tableData, orderBy, candidateStage, candidateState } = recommend;
    const { stageList, scheduleList } = common;
    const [collapsed, setCollapsed] = useState(!!(query.collapsed && query.collapsed === '1') || '1');
    // const [addVisible, setaddVisible] = useState(false); // 监听添加候选人模态框
    const [candicode, setCandicode] = useState(''); // 更新当前选中候选人candidatecode
    // const [candistage, setCandistage] = useState(''); // 更新当前选中候选人面试阶段
    const [visible, setVisible] = useState(false); // 监听设置筛选结果模态框
    const [sorters, setSorters] = useState(''); // 排序储存
    const [filter, setFilter] = useState({}); // 排序储存
    // 获取登陆人公司id
    const user = localStorage.getItem('user');
    const { companyId } = user ? JSON.parse(user) : {};
    const userCompanyId = companyId;
    // 获取参数
    const { getFieldsValue } = form;
    const getSearchData = pageNo => {
        // 方法自动获取高级搜索表单参数
        const { candidateName, recruitCode, companyId: companyIds, addtime, candidateLeaderId = '' } = getFieldsValue();
        // 接口传参参数
        const payload = {
            candidateStage,
            candidateState,
            pageNo: pageNo || pagination.current,
            pageSize: pagination.pageSize,
            orderByField: orderBy,
            // 高级搜索字段
            candidateName,
            recruitCode,
            companyId: companyIds || userCompanyId,
            beginTime: !isEmpty(addtime) ? addtime[0].format('YYYY-MM-DD 00:00:00') : '',
            endTime: !isEmpty(addtime) ? addtime[1].format('YYYY-MM-DD 23:59:59') : '',
            candidateLeaderId: candidateLeaderId.split('-')[0]
        };
        return payload;
    };
    // 接口请求
    const fetchList = (ctx = {}) => {
        const { pageNo = null } = ctx;
        dispatch(
            deepTrim({
                type: 'recommend/fetchRecommendList',
                payload: getSearchData(pageNo)
            })
        );
    };
    // 排序功能
    const tableChange = (paginations, filters, sorter) => {
        let orderBys;
        let sorterField;
        if (sorter && sorter.field && sorter.order) {
            if (sorter.field === 'createTime') {
                sorterField = 'create_time';
            }
            const order = sorter.order.trim().split('end')[0];
            orderBys = `${sorterField} ${order}`;
        } else if (typeof sorters === 'string') {
            dispatch({
                type: 'recommend/save',
                payload: {
                    orderBy: ''
                }
            });
        }
        dispatch({
            type: 'recommend/save',
            payload: {
                orderBy: orderBys || '',
                candidateStage: (filters && filters.candidateStageValue) || [], // 筛选阶段
                candidateState: (filters && filters.candidateStateValue) || [], // 筛选状态
                pagination: {
                    ...recommend.pagination,
                    ...paginations
                }
            }
        });
        // 新的分页组件无法自动回到第一页的bug修复
        if (sorter && sorters !== sorter) {
            setSorters(sorter);
            dispatch({
                type: 'recommend/save',
                payload: {
                    orderBy: orderBys || '',
                    candidateStage: (filters && filters.candidateStageValue) || [], // 筛选阶段
                    candidateState: (filters && filters.candidateStateValue) || [], // 筛选状态
                    pagination: {
                        ...recommend.pagination,
                        current: 1
                    }
                }
            });
        }
        if (filters && JSON.stringify(filter) !== JSON.stringify(filters)) {
            setFilter(filters);
            dispatch({
                type: 'recommend/save',
                payload: {
                    orderBy: orderBys || '',
                    candidateStage: (filters && filters.candidateStageValue) || [], // 筛选阶段
                    candidateState: (filters && filters.candidateStateValue) || [], // 筛选状态
                    pagination: {
                        ...recommend.pagination,
                        current: 1
                    }
                }
            });
        }
    };

    // 组件卸载时候 清空表单请求参数（高级搜索内容、分页、排序字段）
    useEffect(
        () => () => {
            dispatch({
                type: 'recommend/save',
                payload: {
                    pagination: {
                        ...pagination,
                        pageSize: 10,
                        current: 1
                    },
                    orderBy: '',
                    candidateState: [],
                    candidateStage: []
                }
            });
        },
        []
    );
    const isFirstRun = useRef(true);
    // 每当分页数、页面条数、排序、筛查项改变时均应该重新请求表格数据
    useEffect(() => {
        // 第一次不运行
        if (isFirstRun.current) {
            isFirstRun.current = false;
            return;
        }
        if (activeKey === '2') {
            fetchList();
        }
    }, [orderBy, pagination.pageSize, pagination.current, candidateStage, candidateState]);
    // 切换tab更改key值刷新列表
    useEffect(() => {
        if (activeKey === '2') {
            fetchList({ pageNo: 1 });
        }
    }, [activeKey]);

    const tableRef = useRef();
    return (
        // <PageHeaderWrapper>
        <div>
            <CandidateSearchForm
                form={form}
                submit={() => fetchList({ pageNo: 1 })}
                collapsed={collapsed}
                setCollapsed={setCollapsed}
                query={query}
                companyId={companyId}
                route={route}
                candileaderShow // 额外显示招聘负责人
            />

            <div ref={tableRef}>
                <Table
                    bordered={false}
                    scroll={{
                        // x: tableRef.current
                        //     ? tableRef.current.offsetWidth
                        //     : '100%'
                        x: 1400
                    }}
                    columns={columns({
                        stageList,
                        scheduleList,
                        setVisible,
                        setCandicode,
                        // setCandistage,
                        query,
                        candidateStage,
                        candidateState
                    })}
                    loading={loading.models.recommend}
                    dataSource={tableData}
                    rowKey="myRecommendCandidate"
                    onChange={tableChange}
                    pagination={false}
                />
                <Pagination {...pagination} onChange={tableChange} />
            </div>
            {/* <AddCandidate
                Visible={addVisible}
                params={{ companyId, fetchList }}
                // 关闭模态框
                onOk={() => setaddVisible(false)}
                onCancel={() => setaddVisible(false)}
            /> */}
            <SetResult
                Visible={visible}
                params={{
                    candidateCode: candicode,
                    fetchList
                    // candidateStage: candistage
                }}
                // 关闭模态框
                onOk={() => setVisible(false)}
                onCancel={() => setVisible(false)}
            />
        </div>
        // </PageHeaderWrapper>
    );
};
export default connect(({ recommend, common, loading }) => ({
    recommend,
    common,
    loading
}))(Form.create()(List));
